package com.mytijian.openapi.core.utils;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.mytijian.openapi.core.exception.OpenClientNetException;

public class HttpUtils {
	
	private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
	
	/**
	 * http POST 请求。 post 结构体为JSON格式
	 * 
	 * @param url
	 * @param postJSON
	 * @return
	 * @throws Exception
	 */
	public static String doPostJSON(String url, String postJSON) {
		log.info("[APIclient] 调用 url :{}, post-data:{}", url, postJSON);
		CloseableHttpClient client = getHttpClient();
		HttpPost request = new HttpPost(url);
		request.setHeader("Content-Type", "application/json");
		request.setHeader("charset", "UTF-8");
		try {
			if (!StringUtils.isEmpty(postJSON)) {
				StringEntity entity = new StringEntity(postJSON, "UTF-8");
				request.setEntity(entity);
			}
			HttpResponse response = client.execute(request);
			String result = responseToString(response);
			return result;
		} catch (Exception e) {
			log.error("[open-client] [网络调用错误] 异常:{}", e);
			throw new OpenClientNetException(e);
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				log.error("[open-client] [httpclient 关闭异常] 异常:{}", e);
			}
		}
	}

	public static String doGet(String url) {

		log.info("[APIclient] 调用 url :{}", url);
		CloseableHttpClient client = getHttpClient();
		try {
			HttpUriRequest request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			String result = responseToString(response);
			return result;
		} catch (Exception e) {
			log.error("[open-client] [网络调用错误] 异常:{}", e);
			throw new OpenClientNetException(e);
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				log.error("[open-client] [httpclient 关闭异常] 异常:{}", e);
			}
		}
	}

	private static CloseableHttpClient getHttpClient() {
		HttpClientBuilder builder = HttpClientBuilder.create();
		CloseableHttpClient client = builder.build();
		return client;
	}

	private static String responseToString(HttpResponse response) throws IOException {
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}
}
